package com.gurid.service.edu.controller.admin;

import com.gurid.common.base.result.R;
import com.gurid.service.edu.entity.Chapter;
import com.gurid.service.edu.entity.vo.ChapterVo;
import com.gurid.service.edu.service.ChapterService;
import com.gurid.service.edu.service.VideoService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * <p>
 * 课程 前端控制器
 * </p>
 *
 * @author Gurid
 * @since 2024-04-29
 */
@Tag(name = "ChapterController", description = "章节管理" )
@RestController
//@CrossOrigin
@RequestMapping("/admin/edu/chapter")
@Slf4j
public class ChapterController {

    @Autowired
    private ChapterService chapterService;
    @Autowired
    private VideoService videoService;

    @Operation(summary = "新增章节")
    @PostMapping("save")
    public R save(@Parameter(description = "章节对象Chapter", required = true) @RequestBody Chapter chapter) {
        boolean result = chapterService.save(chapter);
        if (result) {
            return R.ok().message("保存成功");
        } else {
            return R.error().message("保存失败");
        }
    }

    @Operation(summary = "查询章节", description = "根据ID查询章节")
    @GetMapping("get/{id}")
    public R getById(
            @Parameter(description = "章节ID", required = true) @PathVariable String id){
        Chapter chapter = chapterService.getById(id);
        if (chapter != null) {
            return R.ok().data("item", chapter);
        } else {
            return R.error().message("数据不存在");
        }
    }

    @Operation(summary = "修改章节", description = "根据ID修改章节")
    @PutMapping("update")
    public R updateById(
            @Parameter(description = "章节对象", required = true) @RequestBody Chapter chapter){
        boolean result = chapterService.updateById(chapter);
        if (result) {
            return R.ok().message("修改成功");
        } else {
            return R.error().message("数据不存在");
        }
    }

    @Operation(summary = "删除章节", description = "根据ID删除章节")
    @DeleteMapping("remove/{id}")
    public R removeById(@Parameter(description = "章节ID", required = true) @PathVariable String id){

        //删除课程视频，调用video中的接口
        videoService.removeMediaVideoByChapterId(id);
        boolean result = chapterService.removeChapterById(id);
        if(result){
            return R.ok();
        }else{
            return R.error().message("删除失败");
        }
    }

    @Operation(summary = "嵌套章节数据列表")
    @GetMapping("nested-list/{courseId}")
    public R nestedListByCourseId(
            @Parameter(name = "courseId", description = "课程ID", required = true)
            @PathVariable String courseId){

        List<ChapterVo> chapterVoList = chapterService.nestedList(courseId);
        return R.ok().data("items", chapterVoList);
    }
}
